package com.bytedance.lucky.security;

import com.bytedance.lucky.error.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zouyaowen
 * @date 2021-02-14 01:07
 */
@Slf4j
public class TokenFilter extends OncePerRequestFilter {

    private final AuthenticationManager authenticationManager;


    public TokenFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            if (SecurityContextHolder.getContext().getAuthentication() == null) {
                // 认证用户信息构建
                TokenAuthentication authentication = new TokenAuthentication(request, response);
                // if (request.getRequestURI().contains(TokenFieldEnum.LOGIN.getField()) || request.getRequestURI().contains(TokenFieldEnum.REGISTER.getField())) {
                //     authentication.setAuthenticated(true);
                //     SecurityContextHolder.getContext().setAuthentication(authentication);
                //     filterChain.doFilter(request, response);
                //     return;
                // }
                // 开始认证及授权处理
                authenticationManager.authenticate(authentication);
            }
            filterChain.doFilter(request, response);
        } catch (ServiceException e) {
            //自定义异常信息通过请求对象属性带到authenticationEntryPoint方法中
            request.setAttribute(TokenFieldEnum.STATUS.getField(), e.getStatus());
            request.setAttribute(TokenFieldEnum.MESSAGE.getField(), e.getMessage());
            throw e;
        } catch (Exception e) {
            log.error("TokenAuthenticationFilter用户信息处理异常...", e);
            throw new AuthenticationServiceException("TokenAuthenticationFilter用户信息处理异常");
        }
    }
}
